﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;

namespace PersonalWebsite.Core.DependencyInjection;

/// <summary>
/// 微软自身的子容器
/// </summary>
public class IOC : IDisposable
{
    private static IServiceProvider? _serviceProvider = null;

    public static void Register(IServiceProvider serviceProvider)
    {
        _serviceProvider ??= serviceProvider;
    }

    public static T GetOption<T>()
        where T : class
    {
        return _serviceProvider!.GetRequiredService<IOptions<T>>().Value;
    }

    public static T Resolve<T>()
        where T : class
    {
        return _serviceProvider!.GetRequiredService<T>();
    }

    public static T KeyResolve<T>(object key)
        where T : class
    {
        return _serviceProvider!.GetRequiredKeyedService<T>(key);
    }

    public void Dispose()
    {
        if (_serviceProvider != null)
            _serviceProvider = null;
    }
}

public static class OptionIOCExtension
{
    public static IServiceCollection AddIOC(this IServiceCollection services)
    {
        var serviceProvider = services.BuildServiceProvider();
        IOC.Register(serviceProvider);

        return services;
    }
}